package com.cn.springcloudwechat.controller.baseRegister;

import com.cn.springcloudwechat.common.ajax.AjaxRes;

import com.cn.springcloudwechat.common.utils.ThreadLocalUtil;
import com.cn.springcloudwechat.common.utils.base.Const;

import com.cn.springcloudwechat.common.utils.weixin.core.WechatHandler;
import com.cn.springcloudwechat.common.utils.weixin.vo.api.Template;
import com.cn.springcloudwechat.common.utils.weixin.vo.event.ScanEvent;
import com.cn.springcloudwechat.controller.base.BaseWeChatController;

import com.cn.springcloudwechat.model.YmUser;

import com.cn.springcloudwechat.model.weixin.user.Follower;
import com.cn.springcloudwechat.model.weixin.user.WxFollower;
import com.cn.springcloudwechat.redis.RedisUtil;
import com.cn.springcloudwechat.service.personalcenter.service.WxFollowerService;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserPointService;
import com.cn.springcloudwechat.service.personalcenter.service.YmUserService;
import com.cn.springcloudwechat.service.vaccine.weixinService.WeiXinService;
import com.cn.springcloudwechat.sms.SmsSendUtils;

import org.apache.commons.lang3.StringUtils;

import org.junit.runners.Parameterized;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

import static com.cn.springcloudwechat.common.utils.RandomNumberUtil.getRandomNumber;


@Controller
@RequestMapping("/web/base/")
public class RegisterController extends BaseWeChatController {
    @Autowired
    WechatHandler wechatHandler;

    @Autowired
    WxFollowerService wxFollowerService;

    @Autowired
    WeiXinService weiXinService;

    @Autowired
    YmUserService ymUserService;

    @Autowired
    YmUserPointService ymUserPointService;


    @RequestMapping("register")
    @ResponseBody
    public AjaxRes register(String random, String userPhone, String password) {
        AjaxRes ajaxRes = getAjaxRes();
        HttpServletRequest request = ThreadLocalUtil.getRequest();
        try {
            String phone = (String) request.getSession().getAttribute("phone");
            String randomNumber = ThreadLocalUtil.getRandomNumber();
            if (!phone.equalsIgnoreCase(userPhone)) {
                ajaxRes.setFailMsg("前后输入的手机号码不一致");
                System.out.println("前后输入的手机号码不一致");
            } else {
                if (randomNumber.equalsIgnoreCase(random)) {
                    YmUser ymUser = ymUserService.getUserByPhone(userPhone);
                    if (ymUser == null) {
                        String openid = (String) request.getSession().getAttribute("openid");
                        if (openid == null) {
                            ajaxRes.setFailMsg("openId错误");
                            System.out.println("openId从session中未获取到");
                        } else {
                            WxFollower wxFollower = wxFollowerService.getWxFollower(openid);
                            if (wxFollower == null) {
                                Follower follower = weiXinService.getWXUserByOpenId(openid);
                                wxFollower = wxFollowerService.castWxFollower(follower);
                                wxFollowerService.insert(wxFollower);
                            }

                            //插入用户表
                            ymUserService.insertUserByWx(wxFollower, password, userPhone);
                            YmUser user = ymUserService.getUserByOpenId(openid);
                            if (user != null) {
                                //新增用户豆豆
                                ymUserPointService.insertUserPoint(user.getUserId(), "注册成功", 1, "+50");
                                //将微信用户信息存入redis
                                RedisUtil.getInstace().del(openid + "follower");
                                RedisUtil.getInstace().set(openid + "follower", wxFollower);
                                //将用户信息存入redis
                                RedisUtil.getInstace().del(openid + "user");
                                RedisUtil.getInstace().set(openid + "user", ymUser);
                                //将user存入缓存
                                request.getSession().setAttribute("user", user);
                                ajaxRes.setSucceed(1, Const.REGISTER_SUCCESS);
                            } else {
                                System.out.println("未知错误");
                                ajaxRes.setFailMsg("未知错误");
                                throw new IllegalAccessException("未知错误！请稍后再试");
                            }
                        }
                    } else {
                        System.out.println("号码已被使用");
                        ajaxRes.setFailMsg("电话号码已经被注册");
                    }
                } else {
                    ajaxRes.setFailMsg("注册码错误");
                }
            }
        } catch (Exception e) {
            System.out.println("错误");
            e.printStackTrace();
        }
        return ajaxRes;
    }

    /**
     * 微信信息登录
     *
     * @param ajaxRes
     * @return
     */
    @RequestMapping("login")
    public void Login(AjaxRes ajaxRes, HttpServletResponse response, Integer type) {
        HttpServletRequest request = ThreadLocalUtil.getRequest();
        try {
            YmUser ymUser = ThreadLocalUtil.getUser();
            if (ymUser != null) {
                skipHtml(type, response);
            } else {
                String openid = getOpenId();
                YmUser user = ymUserService.getUserByOpenId(openid);
                if (user != null && user.getUserId() != null) {
                    //存入session
                    request.getSession().setAttribute("user", user);

                    skipHtml(type, response);
                } else {
                    request.getSession().removeAttribute("openid");
                    request.getSession().setAttribute("openid", openid);
                    response.sendRedirect("/html/MungBeans/html/register.html");
                }
                System.out.println("当前登录用户:" + user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("getRandom")
    @ResponseBody
    public AjaxRes getRandom(AjaxRes ajaxRes, String phone) {
        logger.info("发送的手机:" + phone);
        String phone1 = (String) ThreadLocalUtil.getRequest().getSession().getAttribute("phone");
        if (StringUtils.isEmpty(phone1)) {
            ThreadLocalUtil.getRequest().getSession().setAttribute("phone", phone);
        }
        YmUser ymUser = ymUserService.getUserByPhone(phone);
        if (ymUser != null) {
            ajaxRes.setFailMsg("该手机号码已经注册");
            logger.info("该手机号码已经注册");
        } else {
            try {
                String randomNumber = getRandomNumber();
                ThreadLocalUtil.setRandomNumber(randomNumber);
                String msg = SmsSendUtils.sendOne(phone, randomNumber);
                System.out.println("短信发送:" + msg);
                if (msg.equalsIgnoreCase("ok")) {
                    ajaxRes.setSucceed(msg);
                } else {
                    ajaxRes.setFailMsg(msg);
                }
            } catch (Exception e) {
                ajaxRes.setFailMsg(e.getMessage());
            }
        }
        return ajaxRes;
    }


    /**
     * 判断不同菜单跳转不同页面
     *
     * @param type
     */
    public void skipHtml(Integer type, HttpServletResponse response) throws IOException {
        if (type == 1) {
            //接种记录
            response.sendRedirect("/html/MungBeans/html/jiezhongjilu.html");
        } else if (type == 2) {
            //附近接种点
            response.sendRedirect("/html/MungBeans/html/serviceStationList.html");
        } else if (type == 3) {
            //疫苗知识
            response.sendRedirect("/html/MungBeans/html/yimiaozhishi2.html");
        } else if (type == 4) {
            //疫苗保险
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 5) {
            //预约挂号
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 6) {
            //咨询医生
            response.sendRedirect("/html/MungBeans/html/zixunOnline.html");
        } else if (type == 7) {
            //宝妈课程
            response.sendRedirect("/html/MungBeans/html/coursepackage.html");
        } else if (type == 8) {
            //积分兑换
            response.sendRedirect("/html/MungBeans/html/shop/index.html");
        } else if (type == 9) {
            //亲子活动
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 10) {
            //联系客户
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 11) {
            //专家咨询
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 12) {
            //教育专线
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 13) {
            //旅游在线
            response.sendRedirect("/html/MungBeans/html/please.html");
        } else if (type == 14) {
            //儿童保险
            response.sendRedirect("/html/MungBeans/html/please.html");
        }
    }


    /**
     * 生成带参数的二维码
     *
     * @param message
     * @param type
     * @param proxyId
     * @param expireSeconds
     */
    @RequestMapping("getImage/{message}/{type}/{proxyId}/{expireSeconds}")
    @ResponseBody
    public AjaxRes getImage(@PathVariable(value = "message", required = true) String message,
                         @PathVariable(value = "type", required = true) String type,
                         @PathVariable(value = "proxyId", required = true) String proxyId,
                         @PathVariable(value = "expireSeconds", required = true) Integer expireSeconds) {
        // type 0为用户1为服务站
        String sceneId = "type=" + type  + "&" + proxyId;
        //0临时 1为永久
        Map<String, Object> map = getQR(message, sceneId, expireSeconds);
        AjaxRes ajaxRes = getAjaxRes();
        Object url = map.get("url").toString();
        /*byte[] bytes = (byte[]) map.get("byte");*/
        System.out.println(url);
        System.out.println("生成的二维码:" + url.toString());
        if(url!=null){
            ajaxRes.setSucceed(url.toString());
        }else{
            ajaxRes.setFailMsg("錯誤");
        }
        return ajaxRes;
    }

    @RequestMapping("test")
    @ResponseBody
    public void get(HttpServletRequest request) {
        Template[] template=new Template[2];
        Template a=new Template();
        a.setName("first");
        a.setValue("恭喜你个傻逼中奖了");
        a.setColor("#00FFFF");
        Template b=new Template();
        b.setName("cardNumber");
        b.setValue("520520520520520");
        b.setColor("#00FFFF");
        template[0]=a;
        template[1]=b;
        sendTemplateMsg("oTO_rv_jqyXuxiCENbyQMcmjU_44", "Pxl8P_7wNwS0nbegYVZsNyvLsXoPRNmoFyGFsj-XaJI", "#FF00FF", null, template);
    }
    @RequestMapping("test1")
    @ResponseBody
    public void get1(HttpServletRequest request) {
        System.out.println(getTemplateId());

    }
}
